package utilities;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

/**
 * Manages the xml configuration
 * @author Arvanitis Ioannis
 */
public class XMLProcessor {
	private String path;
	private DocumentBuilderFactory docbuildfact;
	private DocumentBuilder docbuild;
	private Document doc;
	private TransformerFactory transfact = TransformerFactory.newInstance();
	private Transformer trans;
	private DOMSource xmlDoc;
	private String filename;
    private String filepath;

    /**
     * Creates new form XMLProcessor
     * @param filename Name of the file to process
     * @param filepath Path of the file to process
     */
	public XMLProcessor(String filename, String filepath) {
		this.filename = filename;
        this.filepath = filepath;
	}

    /**
     * reads the specified xml file
     * @return the document asked
     */
	public Document readXML() {
		docbuildfact = DocumentBuilderFactory.newInstance();
		transfact = TransformerFactory.newInstance();
		docbuildfact.setNamespaceAware(true);
		// read xml -> make it doc
		try {
			docbuild = docbuildfact.newDocumentBuilder();
			path = new java.io.File(".").getCanonicalPath();
			path += filepath+"\\"+filename+".xml";
            doc = docbuild.parse(path);
		}
		catch(Exception e) {
			System.out.println(e.getMessage());
		}
		if (doc == null){
			System.out.println("Document "+path+" has no data to parse");	
		}
		return doc;
	}

    /**
     * Writes the given document to xml file
     * @param doc Document to transform
     */
	public void writeXML(Document doc) {
		// write xml with new doc
		try{
			xmlDoc = new DOMSource(doc); 
			trans = transfact.newTransformer();
		}
		catch(TransformerConfigurationException e) {
			System.out.println(e.getMessage());
		}  
		try{
			StreamResult result = new StreamResult(new File(path));
			trans.transform(xmlDoc, result);  
		} 
		catch(Exception e) {
			System.out.println(e.getMessage());
		} 
	}
}
